package com.wstuo.itsm.itsop.itsopuser.dao;


import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.util.StringUtils;

import com.wstuo.itsm.itsop.itsopuser.dto.ITSOPUserQueryDTO;
import com.wstuo.itsm.itsop.itsopuser.entity.ITSOPUser;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.util.MathUtils;
/**
 * 外包客户管理DAO类.
 * @author QXY
 */
public class ITSOPUserDAO extends BaseDAOImplHibernate<ITSOPUser> implements IITSOPUserDAO{

	
	@Autowired
	private IOrganizationDAO organizationDAO;
	

	/**
	 * 分页查找外包客户.
	 * @param qdto
	 * @return PageDTO
	 */
	public PageDTO findITSOPUserPager(ITSOPUserQueryDTO qdto){
		
		final DetachedCriteria dc = DetachedCriteria.forClass(ITSOPUser.class);
		int start=0;
		int limit=10;
		if(qdto!=null){
			
			start=qdto.getStart();
			limit=qdto.getLimit();
			if(StringUtils.hasText(qdto.getOrgName())){
				 dc.add(Restrictions.like("orgName",qdto.getOrgName(),MatchMode.ANYWHERE ));
			}
			
			if(qdto.getLoginName()!=null){//所负责的客户
   			 	 dc.createAlias("technicians", "t");
        		 dc.add(Restrictions.eq("t.loginName", qdto.getLoginName()));
			}
			
			if (StringUtils.hasText( qdto.getOfficePhone()) ){
	              dc.add( Restrictions.like( "officePhone",qdto.getOfficePhone(),MatchMode.ANYWHERE ));
	        }

	        if (StringUtils.hasText( qdto.getEmail() ) ){
	             dc.add( Restrictions.like( "email",qdto.getEmail(),MatchMode.ANYWHERE));
	        }
	        
	        if(qdto.getTypeNo()!=null){
	        	 dc.createAlias("type", "tp");
	        	 dc.add( Restrictions.eq("tp.dcode", qdto.getTypeNo()));
	        }
			
			//排序
			if(StringUtils.hasText(qdto.getSord()) && StringUtils.hasText(qdto.getSidx())){
				 if(qdto.getSord().equals("desc"))
		         	dc.addOrder(Order.desc(qdto.getSidx()));
		         else
		         	dc.addOrder(Order.asc(qdto.getSidx()));
			}else{
				
				dc.addOrder(Order.desc("orgNo"));
			}
		}
        return super.findPageByCriteria(dc, start, limit);
	}


	 /**
	  * 重写保存方法.
	  */
     @Override
     public void save(ITSOPUser entity){
    		if(entity.getOrgNo()==null || entity.getOrgNo()==0){
         		entity.setOrgNo(organizationDAO.getLatestOrganizationNo());
         	}else{
         		
         		if(entity.getOrgNo()>organizationDAO.getLatestOrganizationNo()){
         			
         			organizationDAO.setLatesOrganizationNo(entity.getOrgNo()+1);
         		}
         	}
    		organizationDAO.increment();
    		
         	super.save(entity);
     }

     /**
      * 查询与我相关的客户
      * @param qdto ITSOPUserQueryDTO
      * @return 与我相关的全部客户List
      */
    @SuppressWarnings("unchecked")
	public List<ITSOPUser> findMyRelatedCustomer(String loginName){
    	 final DetachedCriteria dc = DetachedCriteria.forClass(ITSOPUser.class);
    	 if(loginName!=null){//所负责的客户
			 	 dc.createAlias("technicians", "t");
    		 dc.add(Restrictions.eq("t.loginName", loginName));
    	 }
    	 List<ITSOPUser> res = 
    			getHibernateTemplate().executeFind(new HibernateCallback<List<ITSOPUser>>(){
    				public List<ITSOPUser> doInHibernate(Session session)
    						throws HibernateException, SQLException {
    					Criteria c = dc.getExecutableCriteria(session);
    					c.setCacheRegion("myRelatedCustomer");
    					c.setCacheable(true);
    					return c.list();
    				}
    			});
    	return res;
     }

	public Long countAllITSOPNumber() {
		final DetachedCriteria dc = DetachedCriteria.forClass(ITSOPUser.class);
		dc.setProjection(Projections.rowCount());
		Criteria criteria = dc.getExecutableCriteria(getSession());
		String result = criteria.uniqueResult().toString();
		if( MathUtils.isNum(result) ){
			return Long.parseLong(result);
		}
		return 0l;
	}
	
}
